﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using SoftMedia.Opcion.Web.Models;

using SoftMedia.Opcion.Web.OpcionService;

namespace SoftMedia.Opcion.Web.Controllers
{
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }
        public void ClientSessionAuthenticate(OpcionService.ClientesPorDocumento_Result rs)
        {
            Session["Usuario"] = rs.nombre;
            Session["codper"] = rs.codper;
            Session["OpcionService.ContratosPorDocumento_Result.cliente"] = rs;
        }


        #region LogOn/Off

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult _LogOn()
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult _LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var rs = MembershipService.ValidateUser(model.UserName, model.Password);
                ///AQUI VOLAMOS lA VALIDACION y AGREGAMOS LOGICA DE NEGOCIO YAY!
                if (rs != null)
                {
                    ClientSessionAuthenticate(rs);
                    FormsService.SignIn(model.UserName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Contratos", "Asociado", new { id = Session["codper"].ToString() });
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Las credenciales son incorrectas");
                }
            }

            // If we got this far, something failed, redisplay form
            return View("LogOn", model);
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var rs = MembershipService.ValidateUser(model.UserName, model.Password);
                ///AQUI VOLAMOS lA VALIDACION y AGREGAMOS LOGICA DE NEGOCIO YAY!
                if (rs != null)
                {
                    ClientSessionAuthenticate(rs);
                    FormsService.SignIn(model.UserName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Contratos", "Asociado", new { id = model.UserName });
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************
        [Authorize]
        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }



        #endregion


        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = 3;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                OpcionClient svc = new OpcionClient();

                if ('T' == svc.CambioPassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Alguna de las contraseñas proporcionadas son invalidas");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = 3;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        // **************************************
        // URL: /Account/UpdateAccountInfo
        // **************************************

        [Authorize]
        public ActionResult ChangeInfo()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangeInfo(ChangeInfoModel model)
        {
            if (ModelState.IsValid)
            {
                OpcionClient svc = new OpcionClient();

                try
                {
                    svc.EnviarEmail("", "", "", model.Body, model.SeguimientoEmail);
                    return RedirectToAction("ChangeInfoSuccess");
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Alguna de los datos proporcionadas son invalidos");
                }

            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = 3;
            return View(model);
        }

        public ActionResult ChangeInfoSuccess()
        {
            return View();
        }

    }
}
